﻿using fabao.Common;
using fabao.SqlSugar;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Microsoft.Extensions.DependencyInjection
{
    public static class SqlSugarExtend
    {
        public static void AddSqlSugarServices(this IServiceCollection services)
        {
            string conn = ConfigSettings.Get<string>("ConnectionStrings:Conn");
            string dbType = ConfigSettings.Get<string>("ConnectionStrings:DbType");
            DbType type = new DbType();
            if (dbType.Equals("sqlserver"))
                type = DbType.SqlServer;
            else
                type = DbType.MySql;
            services.AddSingleton<ISqlSugarClient>(new SqlSugarScope(new ConnectionConfig
            {
                ConnectionString = conn,
                DbType = type,
                InitKeyType = InitKeyType.Attribute,//从特性读取主键和自增列信息
                IsAutoCloseConnection = true,//开启自动释放模式

            },
            db =>
            {

                db.Aop.OnLogExecuting = (sql, pars) =>
                {

                    //获取原生SQL推荐 5.1.4.63  性能OK
                    //Console.WriteLine(UtilMethods.GetNativeSql(sql, pars));

                    //获取无参数化SQL 对性能有影响，特别大的SQL参数多的，调试使用
                    //Console.WriteLine(UtilMethods.GetSqlString(DbType.SqlServer, sql, pars));
#if DEBUG
                    var originColor = Console.ForegroundColor;
                    if (sql.StartsWith("SELECT", StringComparison.OrdinalIgnoreCase))
                        Console.ForegroundColor = ConsoleColor.Green;
                    if (sql.StartsWith("UPDATE", StringComparison.OrdinalIgnoreCase) || sql.StartsWith("INSERT", StringComparison.OrdinalIgnoreCase))
                        Console.ForegroundColor = ConsoleColor.Yellow;
                    if (sql.StartsWith("DELETE", StringComparison.OrdinalIgnoreCase))
                        Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("【" + DateTime.Now + "——执行SQL】\r\n" + UtilMethods.GetSqlString(type, sql, pars) + "\r\n");
                    Console.ForegroundColor = originColor;
#endif
                };

                //注意多租户 有几个设置几个
                //db.GetConnection(i).Aop

            }

            ));



            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }
            services.AddScoped(typeof(IRepository<>), typeof(Repository<>)); // 注入仓储
            //services.AddTransient<IUnitOfWork, SqlSugarUnitOfWork>();
        }
    }
}
